import React, { useState, useEffect } from "react";
import { Modal, Input, Space, Button, message, Segmented } from "antd";
import { PlusOutlined, MinusCircleOutlined, AimOutlined, HomeOutlined, UserOutlined } from "@ant-design/icons";
import { invoke } from "@tauri-apps/api/core";
import { useLoading } from "../../components/LoadingProvider";

const typeOptions = ["tcp", "udp", "http", "tcpmux"];

const EditProxieModal: React.FC<{
  service: any;
  onCancel: () => void;
  onSuccess: () => void;
}> = ({ service, onCancel, onSuccess }) => {
  const [editing, setEditing] = useState<any>({ ...service });
  const [domains, setDomains] = useState<string[]>([...(service.custom_domains || [])]);
  const { showLoading, hideLoading } = useLoading();

  useEffect(() => {
    setDomains([...(service.custom_domains || [])]);
  }, [service]);

  const validate = () => {
    if (!editing.name?.trim()) {
      message.error("别名不能为空");
      return false;
    }
    if (!editing.local_ip?.trim()) {
      message.error("Host 不能为空");
      return false;
    }
    const port = Number(editing.local_port);
    if (!port || port < 1 || port > 65535) {
      message.error("端口必须是 1-65535");
      return false;
    }

    if ((editing.proxy_type === "tcp" || editing.proxy_type === "udp") &&
        (editing.remote_port === undefined || editing.remote_port < 0 || editing.remote_port > 65535)) {
      message.error("远程端口必须是 0-65535");
      return false;
    }

    if ((editing.proxy_type === "http" || editing.proxy_type === "https" || editing.proxy_type === "tcpmux") &&
        (!domains || domains.length === 0 || domains.every(d => d.trim() === ""))) {
      message.error("请至少添加一个域名");
      return false;
    }

    return true;
  };

  const handleSave = async () => {
    if (!validate()) return;
    showLoading()


    const payload: any = { ...editing };

    // 根据 proxy_type 保留特有字段
    switch (editing.proxy_type) {
      case "tcp":
      case "udp":
        payload.remote_port = Number(editing.remote_port) || 0;
        delete payload.multiplexer;
        delete payload.routeByHTTPUser;
        payload.custom_domains = [];
        break;
      case "http":
      case "https":
        payload.custom_domains = domains.filter(d => d.trim() !== "");
        delete payload.remote_port;
        delete payload.multiplexer;
        delete payload.routeByHTTPUser;
        break;
      case "tcpmux":
        payload.multiplexer = editing.multiplexer || "httpconnect";
        payload.routeByHTTPUser = editing.routeByHTTPUser || "";
        payload.custom_domains = domains.filter(d => d.trim() !== "");
        delete payload.remote_port;
        break;
    }

    let result: any = await invoke("save_proxie", { proxy: payload });
    if (result.code) {
      message.success("修改成功");
      onSuccess();
    } else {
      message.error(result.msg || "保存失败");
    }
    hideLoading();
  };

  const handleAddDomain = () => setDomains([...domains, ""]);
  const handleDomainChange = (i: number, val: string) => {
    const copy = [...domains];
    copy[i] = val;
    setDomains(copy);
  };
  const handleRemoveDomain = (i: number) =>
    setDomains(domains.filter((_, idx) => idx !== i));

  return (
    <Modal
      title={`修改服务 - ${editing.name}`}
      visible={true}
      onOk={handleSave}
      onCancel={onCancel}
      okText="保存"
      cancelText="取消"
    >
      <Space direction="vertical" style={{ width: "100%" }}>
        <Input
          addonBefore="ID"
          value={editing.id}
          disabled
        />
        <Segmented
          options={typeOptions.map((p) => ({ label: p.toUpperCase(), value: p }))}
          value={editing.proxy_type} // 使用小写
          onChange={(val) => setEditing({ ...editing, proxy_type: val as string })}
          disabled={true}
        />
        <Input
          addonBefore={
            <>
              <UserOutlined style={{ color: "#1890ff" }} />
            </>
          }
          placeholder="请输入别名"
          value={editing.name}
          onChange={(e) => setEditing({ ...editing, name: e.target.value })}
        />
        <Input
          addonBefore={
            <>
              <HomeOutlined style={{ color: "#52c41a" }} />
            </>
          }
          placeholder="请输入本地IP"
          value={editing.local_ip}
          onChange={(e) => setEditing({ ...editing, local_ip: e.target.value })}
        />
        <Input
          addonBefore={
            <>
              <AimOutlined style={{ color: "#1890ff" }} />
            </>
          }
          placeholder="请输入本地端口"
          type="number"
          value={editing.local_port}
          onChange={(e) => setEditing({ ...editing, local_port: Number(e.target.value) })}
        />
 
  
        {/* TCP/UDP 特有 remotePort */}
        {(editing.proxy_type === "tcp" || editing.proxy_type === "udp") && (
          <Input
            addonBefore="远程端口"
            type="number"
            value={editing.remote_port || 0}
            onChange={(e) => setEditing({ ...editing, remote_port: Number(e.target.value) })}
          />
        )}

        {/* TCMPUX 特有 multiplexer + routeByHTTPUser */}
        {editing.proxy_type === "tcpmux" && (
          <>
            <Input
              addonBefore="Multiplexer"
              value={editing.multiplexer || "httpconnect"}
              onChange={(e) => setEditing({ ...editing, multiplexer: e.target.value })}
              disabled={true}
            />
            <Input
              addonBefore="RouteByHTTPUser"
              value={editing.routeByHTTPUser || ""}
              onChange={(e) => setEditing({ ...editing, routeByHTTPUser: e.target.value })}
            />
          </>
        )}

        {/* HTTP/HTTPS/TCMPUX 特有域名 */}
        {(editing.proxy_type === "http" ||
          editing.proxy_type === "https" ||
          editing.proxy_type === "tcpmux") &&
          domains.map((domain, idx) => (
            <Space key={idx} style={{ width: "100%" }}>
              <Input
                value={domain}
                placeholder="http://*.frp.koalaboys.cn"
                onChange={(e) => handleDomainChange(idx, e.target.value)}
              />
              <MinusCircleOutlined
                onClick={() => handleRemoveDomain(idx)}
                style={{ color: "red" }}
              />
            </Space>
          ))}

        {(editing.proxy_type === "http" ||
          editing.proxy_type === "https" ||
          editing.proxy_type === "tcpmux") && (
          <Button type="dashed" block icon={<PlusOutlined />} onClick={handleAddDomain}>
            添加域名
          </Button>
        )}
      </Space>
    </Modal>
  );
};

export default EditProxieModal;
